package com.cac.demo.controller.dispatchSearch;


import com.cac.demo.controller.CallInterFace.SendMaterialInterface;
import com.cac.demo.newCode.cemop.service.CemopService;
import com.cac.demo.service.dispatchSearch.MsDeliveryPackageInfoService;


import com.cac.demo.util.adapter.ComUtil;
import com.cac.demo.util.adapter.ResponseMsg;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/MsDeliveryPackageInfoRest")
@Slf4j
public class MsDeliveryPackageInfoRest {

    @Autowired
    private MsDeliveryPackageInfoService msDeliveryPackageInfoService;

    @Autowired
    private SendMaterialInterface sendMaterialInterface;

    @Autowired
    private Environment environment;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;
    @Value("${pathProperty.isTest}")
    private boolean isTest;
    @Resource
    private CemopService cemopService;
    //配送物料查询信息
    @PostMapping("/deliveryMaterial")
    public PageInfo deliveryMaterial(@RequestBody HashMap param) {
        HashMap queryParam = (HashMap) param.get("queryParam");
        HashMap page = (HashMap) param.get("page");
        int startPage = Integer.parseInt(page.get("currentPage").toString());
        int pageSize = Integer.parseInt(page.get("pageSize").toString());
        return msDeliveryPackageInfoService.deliveryMaterial(startPage, pageSize, queryParam);
    }

    @PostMapping("/waitingDispatch")
    public PageInfo waitingDispatch(@RequestBody HashMap param) {
        HashMap queryParam = (HashMap) param.get("queryParam");
        HashMap page = (HashMap) param.get("page");
        int startPage = Integer.parseInt(page.get("currentPage").toString());
        int pageSize = Integer.parseInt(page.get("pageSize").toString());
        return msDeliveryPackageInfoService.waitingDispatch(startPage, pageSize, queryParam);
    }
    @PostMapping("queryNoDaliyTimeAoByCarCode")
    public List<HashMap> queryNoDaliyTimeAoByCarCode(@RequestBody HashMap map){
        return msDeliveryPackageInfoService.queryNoDaliyTimeAoByCarCode(map);
    }

    @PostMapping("querySendMaterial")
    public List<HashMap> querySendMaterial(@RequestBody HashMap map){
        return msDeliveryPackageInfoService.querySendMaterial(map);
    }

    //托盘装车
    @PostMapping("palletInCar")
    public ResponseMsg palletInCar(@RequestBody Map map){
        if (map.get("carCode").equals("") || map.get("carCode").toString().isEmpty()) {
            return new ResponseMsg<>().setRetCode("201").setMessage("请先输入小车条码！");
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String opUserCode = (String) request.getSession().getAttribute("account");
        if(Objects.isNull(opUserCode)){
            return new ResponseMsg<>().setRetCode("201").setMessage("登录过期，请重新登录");
        }
        //判断当前托盘内数量是否为零
        List<String> toolCodes = (List<String>) map.get("toolCodes");
        if(toolCodes.size()==0){
            return new ResponseMsg<>().setRetCode("201").setMessage("托盘为空");
        }


        String carCode = (String) map.get("carCode");
        //判断当前小车是否存在已经装车但未配送的数据
        String groupCode = msDeliveryPackageInfoService.getCarGroupCode(carCode);
        if(groupCode==null||"".equals(groupCode)){
            groupCode = ComUtil.getId();
        }
        return msDeliveryPackageInfoService.deliveryPackage(carCode, toolCodes, groupCode);
    }

    //配送
    @PostMapping("/insertMsMatchInfo")
    public ResponseMsg<String> deliveryPackage(@RequestBody Map map) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        if (map.get("carCode").equals("") || map.get("carCode").toString().isEmpty()) {
            responseMsg.setRetCode("201").setMessage("请先输入小车条码！");
            return responseMsg;
        }
        //6-26lqc
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String opUserCode = (String) request.getSession().getAttribute("account");
        if(Objects.isNull(opUserCode)){
            return responseMsg.setRetCode("201").setMessage("登录过期，请重新登录");
        }
        String carCode = (String) map.get("carCode");
        //yebo 根据小车查询装车的组号
        String groupCode = msDeliveryPackageInfoService.getCarGroupCode(carCode);
        if(groupCode==null||"".equals(groupCode)){
            responseMsg.setRetCode("201").setMessage("该小车已经配送，请确认！");
            return responseMsg;
        }
        //判断当前装车的小车的工作包是是否存在没下日计划的
        if(msDeliveryPackageInfoService.queryPackageExistsDaliyPlan(carCode)){
            String aoCodes = msDeliveryPackageInfoService.queryAoExistsDaliy(carCode);
            responseMsg.setRetCode("201").setMessage("当前已装车的AO存在未下日计划的AO！未下日计划AO如下："+aoCodes);
            return responseMsg;
        }
        //校验配送小车的物料是否重复
        if(msDeliveryPackageInfoService.existsRepeatDelivery(groupCode)){
            return responseMsg.setRetCode("201").setMessage("当前配送的物料生成的交接单存在重复数据，请查看ms_delivery_repeat_check表");
        }
        //校验配送过去的物料数量是否超过需求数量
        HashMap re = msDeliveryPackageInfoService.checkSendQty(groupCode);
        if("201".equals(re.get("retCode"))){
            return responseMsg.setRetCode("201").setMessage((String)re.get("retMsg"));
        }
        //查询交接单ID
        List<String> planIds = msDeliveryPackageInfoService.selectPlanIds(carCode);
        //cemop上传配送数据
        ResponseMsg<Object> objectResponseMsg = cemopService.sendMaterialInfo(planIds);
        //更新当前小车配送状态
        int cnt = msDeliveryPackageInfoService.updateWorkbinCar(carCode);
        HashMap paramMap = new HashMap();
        //判断当前环境是否为测试环境
        String isTest = environment.getProperty("pathProperty.isTest");
        if("true".equals(isTest)){
            paramMap.put("dmsCode", "ms_gzbps_test");
        }else{
            paramMap.put("dmsCode", "ms_gzbps");
        }
//        //网闸查询数据SQL所需条件
//        paramMap.put("delivery_plan_code", groupCode);
//        HashMap interfaceMap = new HashMap();
//        interfaceMap.put("code", "getMatchData");
//        interfaceMap.put("name", "获取数据配套场景的配套数据");
//        interfaceMap.put("parameters", paramMap);
//        //发送文件所需func
//        interfaceMap.put("func", environment.getProperty("dispatch.func"));
//        interfaceMap.put("sendScenario", "物料配送");
//        log.info("=====================" + interfaceMap.toString());
//        log.info(objectResponseMsg.toString());
//        HashMap rsl = sendMaterialInterface.SendFileInterface(interfaceMap);
//        if (rsl.get("retCode").equals("200")) {
//            responseMsg.setRetCode("200").setMessage("配送数据保存成功！");
//        } else {
//            responseMsg.setRetCode("201").setMessage("物料数据上传MES失败！");
//        }
        return responseMsg;
    }

    //单条配送,单条配送没有校验是否下日计划
    @PostMapping("deliveryPackageSingle")
    public ResponseMsg<String> deliveryPackageSingle(@RequestBody List<HashMap> list){
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String groupCode = ComUtil.getId();
        for(HashMap map : list){
            String wmsDeliveryPlanId = map.get("wmsDeliveryPlanId").toString();
            //更新当前小车配送状态
            int cnt = msDeliveryPackageInfoService.updateWorkbinCarByDeliveryPlanId(wmsDeliveryPlanId,groupCode);
            //更新交接单组号
            msDeliveryPackageInfoService.udpateDeliveryGroupCode(wmsDeliveryPlanId,groupCode);
        }
        //校验配送小车的物料是否重复
        if(msDeliveryPackageInfoService.existsRepeatDelivery(groupCode)){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseMsg.setRetCode("201").setMessage("当前配送的物料生成的交接单存在重复数据，请查看ms_delivery_repeat_check表");
        }
        //校验配送过去的物料数量是否超过需求数量
        HashMap re = msDeliveryPackageInfoService.checkSendQty(groupCode);
        if("201".equals(re.get("retCode"))){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseMsg.setRetCode("201").setMessage((String)re.get("retMsg"));
        }
        HashMap paramMap = new HashMap();
        paramMap.put("dmsCode", "ms_gzbps");
        //网闸查询数据SQL所需条件
        paramMap.put("delivery_plan_code", groupCode);
        HashMap interfaceMap = new HashMap();
        interfaceMap.put("code", "getMatchData");
        interfaceMap.put("name", "获取数据配套场景的配套数据");
        interfaceMap.put("parameters", paramMap);
        //发送文件所需func
        interfaceMap.put("func", environment.getProperty("dispatch.func"));
        interfaceMap.put("sendScenario", "物料配送");
        log.info("=====================" + interfaceMap.toString());
        //文件上传ERP
        HashMap rsl = sendMaterialInterface.SendFileInterface(interfaceMap);
        if (rsl.get("retCode").equals("200")) {
            responseMsg.setRetCode("200").setMessage("配送数据保存成功！");
        } else {
            responseMsg.setRetCode("201").setMessage("物料数据上传MES失败！");
        }
        return responseMsg;
    }

    //物料查询配送
    @PostMapping("materialSend")
    public ResponseMsg materialSend(@RequestBody List<HashMap> list){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ResponseMsg<String> responseMsg = new ResponseMsg<String>();
        String opUserCode = (String) request.getSession().getAttribute("account");
        if(Objects.isNull(opUserCode)){
            return new ResponseMsg<>().setRetCode("201").setMessage("登录过期，请重新登录");
        }
        String IP = null;
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        log.info("000000000000:"+list.toString());
//        if(list.isEmpty()||list.size()==0){
//            return responseMsg.setRetCode("201").setMessage("请先选择一条记录！");
//        }

        String groupCode = ComUtil.getId();
        responseMsg = msDeliveryPackageInfoService.createDelivery(list,groupCode,opUserCode,IP);

        //校验配送小车的物料是否重复
        if(msDeliveryPackageInfoService.existsRepeatDelivery(groupCode)){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseMsg.setRetCode("201").setMessage("当前配送的物料生成的交接单存在重复数据，请查看ms_delivery_repeat_check表");
        }
        //校验配送过去的物料数量是否超过需求数量
        HashMap re = msDeliveryPackageInfoService.checkSendQty(groupCode);
        if("201".equals(re.get("retCode"))){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseMsg.setRetCode("201").setMessage((String)re.get("retMsg"));
        }
        HashMap paramMap = new HashMap();
        paramMap.put("dmsCode", "ms_gzbps");
        //网闸查询数据SQL所需条件
        paramMap.put("delivery_plan_code", groupCode);
        HashMap interfaceMap = new HashMap();
        interfaceMap.put("code", "getMatchData");
        interfaceMap.put("name", "获取数据配套场景的配套数据");
        interfaceMap.put("parameters", paramMap);
        //发送文件所需func
        interfaceMap.put("func", environment.getProperty("dispatch.func"));
        interfaceMap.put("sendScenario", "物料配送");
        log.info("=====================" + interfaceMap.toString());
        //文件上传ERP
        HashMap rsl = sendMaterialInterface.SendFileInterface(interfaceMap);
        if (rsl.get("retCode").equals("200")) {
            responseMsg.setRetCode("200").setMessage("配送数据保存成功！");
        } else {
            responseMsg.setRetCode("201").setMessage("物料数据上传MES失败！");
        }
        return responseMsg;
    }


    //定时上传配套状态
    @GetMapping("/upDeliveryStatus")
    @Scheduled(cron = "0 0 0/3 * * ?")
    public HashMap upDeliveryStatus() {
        //网闸数据打包接口所需参数，以及发送文件所需func
        HashMap paramMap = new HashMap();
        //网闸查询场景编码
//        if(isTest){
//            paramMap.put("dmsCode", "ms_scptztcs");
//        }else {
//            paramMap.put("dmsCode", "ms_scptzt");
//        }
        paramMap.put("dmsCode", "ms_scptzt");
        //网闸查询数据SQL所需条件
        paramMap.put("match_status", "02");
        HashMap interfaceMap = new HashMap();
        interfaceMap.put("code", "getMatchData");
        interfaceMap.put("name", "定时上传数据配套场景的配套数据");
        interfaceMap.put("parameters", paramMap);
        //发送文件所需func
        interfaceMap.put("func", "101-MES-MaterialState");
        interfaceMap.put("sendScenario", "定时上传配套状态");
        log.info("==========定时上传配套状态===========" + interfaceMap.toString());
        //文件上传ERP
        HashMap rsl = sendMaterialInterface.SendFileInterface(interfaceMap);
        log.info("==========定时上传配套状态===========" + rsl.toString());
        return rsl;
    }



    //查询已配套工作包ao信息
//    @PostMapping("/searchPackageAo")
//    @Transactional
//    public ResponseMsg<QueryRespBean<List<HashMap>>> searchPackageAo(@RequestBody Map map) {
//        ResponseMsg<QueryRespBean<List<HashMap>>> responseMsg = new ResponseMsg<>();
//        String param = JSON.toJSONString(map.get("pageParameter"));
//        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
//        QueryReqBean<List<HashMap>> queryReqBean = new QueryReqBean<>();
//        queryReqBean.setPageParameter(pageParameter);
//        QueryRespBean<List<HashMap>> result = msDeliveryPackageInfoService.searchPackageAo(queryReqBean);
//        responseMsg.setResponseBody(result);
//        return responseMsg;
//    }


    //查询工作包下托盘信息
    @PostMapping("/searchByPackageCode")
    public ResponseMsg<HashMap> selectByPackageCode(@RequestBody Map map) {
        ResponseMsg<HashMap> responseMsg = new ResponseMsg<>();
        String packageCode = (String) map.get("packageCode");
        responseMsg.setResponseBody(msDeliveryPackageInfoService.selectByPackageCode(packageCode));
        return responseMsg;
    }

    //查询配送任务数量信息
    @PostMapping("/countSearch")
    public ResponseMsg<String> countSearch() {
        ResponseMsg responseMsg = new ResponseMsg();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String time = formatter.format(date);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>time:" + formatter.format(date));
        HashMap result = msDeliveryPackageInfoService.countSearch(time);
        if (result != null) responseMsg.setResponseBody(result).setRetCode("200");
        else responseMsg.setRetCode("201").setMessage("暂无数据");
        return responseMsg;
    }
}
